<template>
  <div class="app-container">
    <!--搜索栏start-->
    <div class="searchMultiple" style="width: 100%">
      <el-input
        v-model="searchData.name"
        placeholder="住户姓名"
        clearable
        class="input"
        style="width: 10%"
        @change="nameInputChange"
      />
      <el-input
        v-model="searchData.phone"
        placeholder="住户手机号"
        clearable
        class="input"
        style="width: 10%"
        @change="phoneInputChange"
      />
      <el-input
        v-model="searchData.xiaoquName"
        placeholder="小区名称"
        clearable
        class="input"
        style="width: 10%"
        @change="xiaoquNameInputChange"
      />
      <el-button style="margin-left: 1%" type="primary" icon="el-icon-close" @click="clearContent()">清空</el-button>
      <el-button style="margin-left: 1%" type="primary" icon="el-icon-search" @click="search()" @keydown="enterEvent()">搜索</el-button>
      <el-button style="float: right" size="medium" type="danger" icon="el-icon-delete" @click="deletePatch()">批量删除</el-button>
      <el-button style="float: right" size="medium" type="primary" @click="clickAddButton">新增</el-button>
    </div>
    <!--搜索栏end-->

    <!--表格信息start-->
    <div class="tableList">
      <el-table
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
        />
        <el-table-column
          label="序号"
          align="center"
        >
          <template slot-scope="scope">
            <span>{{ (searchData.pageNumber - 1) * searchData.pageSize + scope.$index+1 }} </span>
          </template>
        </el-table-column>
        <el-table-column
          prop="icon"
          label="头像"
          align="center"
        >
          <template slot-scope="scope">
            <img :src="scope.row.icon" width="50" height="50" alt=" ">
          </template>
        </el-table-column>
        <el-table-column
          prop="account"
          label="账号"
          align="center"
        />
        <el-table-column
          prop="name"
          label="姓名"
          align="center"
        />
        <el-table-column
          prop="phone"
          label="手机号"
          align="center"
        />
        <el-table-column
          prop="sex"
          label="性别"
          align="center"
        />
        <el-table-column
          label="操作"
          min-width="130%"
          align="center"
        >
          <template slot-scope="scope">
            <div style="display: flex;flex-direction: row;justify-content: center">
              <el-button type="danger" icon="el-icon-delete" circle @click="deleteById(scope.row.id)" />
              <el-button type="warning" icon="el-icon-edit" circle @click="editHouseHold(scope.row.id)" />
              <el-button type="primary" icon="el-icon-refresh" circle @click="resetPwd(scope.row.account)" />
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!--表格信息end-->

    <!--分页插件start-->
    <el-pagination
      style="margin-top: 1%;display: flex;justify-content: right"
      background
      layout="prev, pager, next"
      :page-size="size"
      :total="total"
      :current-page.sync="searchData.pageNumber"
      @current-change="currentChange"
    />
    <!--分页插件end-->
    <!--新增弹出框start-->
    <el-dialog title="新增用户" :visible.sync="addFormVisible">
      <el-form :model="addForm">
        <el-form-item label="角色类型" label-width="120px">
          <el-radio-group v-model="addForm.type" @change="$forceUpdate()">
            <el-radio :label="1">管理员</el-radio>
            <el-radio :label="3">维修人员</el-radio>
            <el-radio :label="2">普通用户</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="账号" label-width="120px">
          <el-input v-model="addForm.account" autocomplete="off" />
        </el-form-item>
        <el-form-item label="姓名" label-width="120px">
          <el-input v-model="addForm.name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="手机号" label-width="120px">
          <el-input v-model="addForm.phone" autocomplete="off" />
        </el-form-item>
        <el-form-item label="性别" label-width="120px">
          <el-input v-model="addForm.sex" autocomplete="off" />
        </el-form-item>
        <el-form-item label="头像" label-width="120px">
          <el-upload
            class="avatar-uploader"
            action="http://39.106.32.84:8080/PMSystem/upload"
            :headers="uploadHeaders"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="iconUrl" :src="iconUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="insertHouseHold">确 定</el-button>
      </div>
    </el-dialog>
    <!--新增弹出框end-->

    <!--编辑弹出框start-->
    <el-dialog title="编辑" :visible.sync="editFormVisible">
      <el-form :model="editForm">
        <el-form-item label="账号" label-width="120px">
          <el-input :value="editForm.account" autocomplete="off" disabled />
        </el-form-item>
        <el-form-item label="姓名" label-width="120px">
          <el-input v-model="editForm.name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="手机号" label-width="120px">
          <el-input v-model="editForm.phone" autocomplete="off" />
        </el-form-item>
        <el-form-item label="性别" label-width="120px">
          <el-input v-model="editForm.sex" autocomplete="off" />
        </el-form-item>
        <el-form-item label="头像" label-width="120px">
          <el-upload
            class="avatar-uploader"
            action="http://39.106.32.84:8080/PMSystem/upload"
            :headers="uploadHeaders"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="iconUrl" :src="iconUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveEidt">确 定</el-button>
      </div>
    </el-dialog>
    <!--编辑弹出框end-->
  </div>
</template>

<script>
import { addHouseHold, deleteById, deletePatch, editById, getHouseHoldList } from '@/api/houseHold'
import { parseTime } from '@/utils'
import { getToken } from '@/utils/auth'
import { getList } from '@/api/apartment'
import { resetPwd } from '@/api/user'

export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    formatTime(time) {
      return parseTime(time, '{y}-{m}-{d} {h}:{i}')
    }
  },
  data() {
    return {
      list: null,
      xiaoquList: [], // 小区集合
      listLoading: true,
      currentHouseHoldId: '', // 当前住户id
      tableData: [], // 表格数据
      total: 0, // 分页插件总记录数
      size: 0, // 分页插件每页显示个数
      addFormVisible: false, // 新增弹窗是否显示
      editFormVisible: false, // 编辑弹窗是否显示
      searchData: { // 查询参数
        id: null,
        name: null, // 住户姓名
        phone: null, // 住户手机号
        xiaoquName: null, // 小区名称
        pageNumber: 1, // 接口默认的页数
        pageSize: 5 // 接口默认的每页大小
      },
      addForm: {},
      editForm: {},
      houseHoldIds: [],
      uploadHeaders: { Authorization: getToken() }, // 文件上传请求头
      iconUrl: '' // 头像预览url
    }
  },
  created() {
    this.getHouseHold()
    window.addEventListener('keydown', this.enterEvent)
  },
  destroyed() {
    window.removeEventListener('keydown', this.enterEvent, false)
  },
  methods: {
    getHouseHold() {
      console.log(this.searchData.pageSize)
      this.finalSelect()
    },
    search() { // 点击搜索按钮
      this.finalSelect()
    },
    clearContent() { // 清空输入框方法
      this.searchData.name = null
      this.searchData.phone = null
      this.searchData.xiaoquName = null
      this.searchData.pageNumber = 1
      this.getHouseHold()
    },
    deleteById(id) { // 根据小区id删除用户
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteById(id).then(res => {
          if (res.code === 20000) {
            this.$message.success('删除成功！')
            this.calcuPageNumber()
            this.getHouseHold()
            this.total = this.total - 1
          } else {
            this.$message.warning('删除失败！')
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleSelectionChange(val) {
      this.xiaoquIds = []
      val.forEach(value => {
        this.xiaoquIds.push(value.id)
      })
    },
    currentChange(val) { // 点击分页栏方法
      this.searchData.pageNumber = val
      this.finalSelect()
    },
    phoneInputChange(value) { // 住户手机号输入框chang函数
      if (value === '' || value == null) {
        this.searchData.phone = null
      }
    },
    nameInputChange(value) { // 住户名称输入框chang函数
      if (value === '' || value == null) {
        this.searchData.name = null
      }
    },
    xiaoquNameInputChange(value) { // 小区名称输入框chang函数
      if (value === '' || value == null) {
        this.searchData.xiaoquName = null
      }
    },
    handleAvatarSuccess(res) { // 上传成功函数
      this.iconUrl = res.data
      this.addForm.icon = res.data
      this.editForm.icon = res.data
    },
    beforeAvatarUpload(file) { // 上传之前
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    insertHouseHold() { // 添加用户方法
      addHouseHold(this.addForm).then(res => {
        if (res.code === 20000) { // 新增完成之后，来到第一页
          this.$message.success('添加成功!')
          this.searchData.pageNumber = 1
          this.finalSelect() // 跳转到首页
        } else {
          this.$message.error('添加失败!')
        }
        this.addFormVisible = false
      })

      console.log(this.addForm)
    },
    editHouseHold(id) { // 编辑住户按钮,数据回显
      this.currentHouseHoldId = id
      this.editFormVisible = true
      getHouseHoldList({
        id: id
      }).then(res => {
        console.log(res)
        this.editForm = res.data[0]
        this.iconUrl = res.data[0].icon
      })
    },

    resetPwd(account) { // 编辑住户按钮,数据回显
      this.$confirm('确认要重置密码么?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        resetPwd(account).then(res => {
          this.$message.success('重置密码成功，新密码为：123456')
        })
      }).catch(() => {
        this.$refs.multipleTable.clearSelection()
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    calcuPageNumber() { // 计算删除后，跳转的页数
      const lastPage = this.total % this.size === 0 ? Math.floor(this.total / this.size) : Math.d(this.total / this.size) + 1
      if (this.searchData.pageNumber < lastPage) {
        return this.searchData.pageNumber
      } else {
        this.searchData.pageNumber = lastPage
        return 0
      }
    },
    deletePatch() { // 根据id批量删除小区
      const deleteCount = this.xiaoquIds.length
      this.$confirm('此操作将永久删除这些记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deletePatch(this.xiaoquIds).then(res => {
          this.total = this.total - deleteCount
          this.calcuPageNumber()
          this.$message.success('删除成功！')
          this.finalSelect() // 跳转到当前页
        }).catch(() => {
          this.$message.error('删除失败！')
        })
      }).catch(() => {
        this.$refs.multipleTable.clearSelection()
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    finalSelect() { // 封装后的查询列表方法
      getHouseHoldList(this.searchData).then(res => {
        if (res.data.records) {
          this.tableData = res.data.records
          this.total = res.data.total
          this.size = res.data.size
        } else {
          this.tableData = res.data
        }
      })
    },
    enterEvent() {
      console.log('键盘事件')
    },
    saveEidt() {
      editById(this.currentHouseHoldId, this.editForm).then(res => {
        if (res.code === 20000) {
          this.$message.success('修改成功！')
        } else {
          this.$message.error('修改失败！')
        }
        this.editFormVisible = false // 关闭弹出框
        this.finalSelect() // 刷新界面
      }).catch(() => {
        this.editFormVisible = false
        this.$message.error('修改失败！')
      })
    },
    getAllXiaoquList() { // 获取所有小区列表
      return getList(null)
    },
    clickAddButton() { // 点击新增按钮事件
      this.addForm = {}
      this.addForm.type = 2
      this.iconUrl = ''
      this.addFormVisible = true // 显示新增弹出框
      this.getAllXiaoquList().then(res => { // 赋值小区选择框
        this.xiaoquList = res.data
      }) // 获取所有的小区列表
    }
  }
}
</script>

<style lang="scss">
.searchMultiple{
  margin-top: 1%;
  width: 80%;
  .input{
    width: 20%;
    margin-right: 0.5%;
  }
}
.tableList{
  margin-top: 1%;
  height: 50%;
  display: flex;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
